package com.xz.supplierOrder.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xz.common.core.domain.model.LoginUser;
import com.xz.common.utils.DateUtils;
import com.xz.common.utils.SecurityUtils;
import com.xz.purchase.domain.PurchaseProduct;
import com.xz.supplierOrder.domain.SupplierOrderDetail;
import com.xz.supplierOrder.domain.SupplierOrderDetailRecord;
import com.xz.supplierOrder.mapper.SupplierOrderDetailRecordMapper;
import com.xz.supplierOrder.service.ISupplierOrderDetailRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 贸易中间商订单商品出入库记录Service业务层处理
 *
 * @author xz
 * @date 2024-03-04
 */
@Service
public class SupplierOrderDetailRecordServiceImpl extends ServiceImpl<SupplierOrderDetailRecordMapper, SupplierOrderDetailRecord> implements ISupplierOrderDetailRecordService {
  @Autowired
  private SupplierOrderDetailRecordMapper supplierOrderDetailRecordMapper;


  /**
   * 获取单据的出入库记录
   *
   * @param orderId
   * @param orderDetailId
   * @param dataType
   * @return
   */
  @Override
  public List<SupplierOrderDetailRecord> getByOrder(Long orderId, Long orderDetailId, Integer dataType) {
    LambdaQueryWrapper<SupplierOrderDetailRecord> wrapper = Wrappers.lambdaQuery(SupplierOrderDetailRecord.class);
    wrapper.eq(null != orderId,SupplierOrderDetailRecord::getOrderId,orderId);
    wrapper.eq(null != orderDetailId,SupplierOrderDetailRecord::getOrderDetailId,orderDetailId);
    wrapper.eq(null != dataType,SupplierOrderDetailRecord::getDataType,dataType);
    return list(wrapper);
  }

  /**
   * 初始化贸易中间商订单商品出入库记录
   * @param detail
   * @param purchaseProducts
   */
  @Override
  public List<SupplierOrderDetailRecord> initEntityList(SupplierOrderDetail detail, List<PurchaseProduct> purchaseProducts, Integer dataType) {

    LoginUser user = SecurityUtils.getLoginUser();
    List<SupplierOrderDetailRecord> records = new ArrayList<>();
    purchaseProducts.forEach(purchaseProduct -> {
      SupplierOrderDetailRecord record = new SupplierOrderDetailRecord();
      record.setOrderId(detail.getOrderId());
      record.setOrderDetailId(detail.getId());
      record.setPurchaseProductId(purchaseProduct.getId());
      record.setPurchaseId(purchaseProduct.getPurchaseId());
      record.setProductId(purchaseProduct.getProductId());
      record.setDataType(dataType);
      record.setProductNum(purchaseProduct.getInventoryQuantity());
      //填充创建人信息
      record.setCreateBy(user.getUserId());
      record.setCreateTime(DateUtils.getNowDate());
      record.setTenantId(user.getTenantId());
      record.setDeptId(user.getDeptId());
      records.add(record);
    });
    return records;
  }

}
